package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmUpdateDataService;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasProcessDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.PaasFormDataHelper;
import com.xbongbong.paas.help.UserHelp;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.vo.FormDataUpdateVO;
import com.xbongbong.paas.service.PaasFormDataService;
import com.xbongbong.paas.service.ProModelService;
import com.xbongbong.paas.service.dynamic.crm.strategy.DynamicStrategyFactory;
import com.xbongbong.paas.service.dynamic.crm.strategy.MainBusinessDynamicStrategy;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.GaodeGeoHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.domain.entity.ReRollBackEntity;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicUpdateDTO;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.AfterSavePojo;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.formdata.pojo.vo.BeforeUpdateVO;
import com.xbongbong.pro.formdata.pojo.vo.UpdateVO;
import com.xbongbong.pro.message.pojo.dto.ConsistencySyncRabbitMqDTO;
import com.xbongbong.pro.rabbitmq.producer.ConsistencySyncProducer;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.CustomerUserEntity;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.ProjectLogEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.CustomerUserModel;
import com.xbongbong.saas.service.CustomerService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import org.elasticsearch.action.support.WriteRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/02/23 16:03
 */
@Service("customerFormDataUpdateServiceImpl")
public class CustomerFormDataUpdateServiceImpl extends AbstractCrmUpdateDataService {

    private static final Logger LOG = LoggerFactory.getLogger(CustomerFormDataUpdateServiceImpl.class);

    @Resource
    private UserHelp userHelp;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private CustomerService customerService;
    @Resource
    private ConsistencySyncProducer consistencySyncProducer;
    @Resource
    private PaasFormDataService paasFormDataService;
    @Resource
    private ProModelService proModelService;
    @Resource
    private CustomerUserModel customerUserModel;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private DynamicStrategyFactory dynamicStrategyFactory;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;
    @Resource
    private PaasFormDataHelper paasFormDataHelper;
    @Override
    public List<Integer> businessType() {
        return Arrays.asList(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
    }

    @Override
    public void businessImportSetData(FieldAttrEntity fieldAttrEntity, JSONObject oldData, JSONObject newData) {
        // 由各个业务层实现
        //判断导入无需覆盖字段
        if ( Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.CREATOR.getAttr())) {
            newData.put(fieldAttrEntity.getAttr(), oldData.get(fieldAttrEntity.getAttr()));
        }
    }



    @Override
    public UpdateVO update(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        UpdateVO updateVO = null;
        try {
            UserVO userVO = userHelp.getUserName(formDataUpdateDTO.getCorpid(), formDataUpdateDTO.getUserId(), formDataUpdateDTO.getLoginUserName(), beforeUpdateVO.getPaasFormDataEntity().getFlowStatus(), beforeUpdateVO.getPaasFormDataEntity().getCreatorId());
            Integer noApprovalRequired = beforeUpdateVO.getNoApprovalRequired();
            Integer updateLine = 0;
            updateVO = new UpdateVO(noApprovalRequired, formDataUpdateDTO.getDataId(), userVO);
            if ( Objects.equals(noApprovalRequired, 1) ) {
                //TODO 剔除联系人
                JSONObject oldData = oldPaasFormDataEntity.getData();

                Long oldLastConnectTime = FastJsonHelper.getLongOrDefaultFromFormData(oldData, CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), 0L);
                JSONObject data = paasFormDataEntity.getData();
                Long newLastConnectTime = FastJsonHelper.getLongOrDefaultFromFormData(data, CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), 0L);

                data.remove(CustomerManagementEnum.ADD_CONTACT.getAttr());
                FormDataUtil.removeSystemData(data);
                Object richTextData = removeRichText(data);
                if ( oldLastConnectTime > newLastConnectTime ) {
                    data.put(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(),oldLastConnectTime);
                }
                paasFormDataEntity.setData(data);
                CustomerEntityExt customerEntityExt = new CustomerEntityExt();
                BeanUtil.copyProperties(paasFormDataEntity, customerEntityExt);
                updateLine = customerModel.update(customerEntityExt);
                // 设置属性用于返回
                setPartialAttributes(customerEntityExt.getSubFormData(), customerEntityExt.getData(),
                        customerEntityExt.getUpdateTime(), customerEntityExt.getAddTime(), customerEntityExt.getSerialNo(),
                        customerEntityExt.getDepartmentId(), customerEntityExt.getOwnerId(),
                        paasFormDataEntity, beforeUpdateVO);
                updateVO.setPaasFormDataEntity(paasFormDataEntity);
                updateVO.setUpdateLine(updateLine);
                //文件柜数据保存
                saveFile(formDataUpdateDTO, paasFormDataEntity, userVO);
                //富文本数据更新
                updateFormRichText(formDataUpdateDTO, richTextData);
            }
            return updateVO;
        } catch (XbbException e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            throw e;
        } catch (Exception e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            LOG.error("customerFormDataUpdateServiceImpl.update 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }


    @Override
    public FormDataUpdateVO afterSave(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, UpdateVO updateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        String corpid = formDataUpdateDTO.getCorpid();
        Long dataId = formDataUpdateDTO.getDataId();
        Integer businessType = formDataUpdateDTO.getBusinessType();
        try {
            FormDataUpdateVO formDataUpdateVO = new FormDataUpdateVO();
            Integer noApprovalRequired = updateVO.getNoApprovalRequired();
            if (Objects.equals(1, noApprovalRequired)) {
                JSONObject oldData = oldPaasFormDataEntity.getData();
                String oldCustomerName = FastJsonHelper.getStringOrDefaultFromFormData(oldData, CustomerManagementEnum.NAME.getAttr(), "");
                String opObjectName = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntity.getData(), CustomerManagementEnum.NAME.getAttr(), "");
                SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
                BeanUtil.copyProperties(formDataUpdateDTO, saasFormSaveDTO);
                packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                // 处理保存之后的逻辑
                AfterSavePojo afterSavePojo = customerService.afterSave(saasFormSaveDTO);
                SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo = formDataUpdateDTO.getSaasNeedRedundantAttrPoJo();
                List<ValidateDataDTO> needAddValidateDataDTO = null;
                List<ValidateDataDTO> needDelValidateDataDTO = null;
                List<ValidateDataDTO> needUpdateValidateDataDTO = null;
                if (saasNeedRedundantAttrPoJo != null) {
                    needAddValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedAddValidateDataDTO();
                    needDelValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedDelValidateDataDTO();
                    needUpdateValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedUpdateValidateDataDTO();
                }

                // 客户动态
                if(!Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(),formDataUpdateDTO.getDistributorMark())) {
                    MainBusinessDynamicStrategy dynamicStrategy = dynamicStrategyFactory.getMainBusinessDynamicStrategy(ProjectLogEnum.CUSTOMER_UPDATE.getSubType());
                    dynamicStrategy.update(new DynamicUpdateDTO(formDataUpdateDTO, beforeUpdateVO, updateVO));
                }
                // 记录日志
                afterSaveLog(formDataUpdateDTO, paasFormEntity, paasFormDataEntity, oldPaasFormDataEntity, updateVO, beforeUpdateVO);
                // 批量保存联系人
                if (!Objects.isNull(needAddValidateDataDTO) || !Objects.isNull(needDelValidateDataDTO) || !Objects.isNull(needUpdateValidateDataDTO)) {
                    String creatorId = formDataUpdateDTO.getProcessCreatorId();
                    creatorId = StringUtil.isEmpty(creatorId) ? formDataUpdateDTO.getUserId() : creatorId;
                    paasFormDataHelper.batchEditContactForUpdate(saasNeedRedundantAttrPoJo, formDataUpdateDTO.getLoginUser(), creatorId, corpid, dataId, opObjectName, formDataUpdateDTO.getIsImport(), ContactEnum.CUSTOMER_NAME.getAttr(), XbbRefTypeEnum.CONTACT);
                }

                // 客户数据一致性同步
                if (!Objects.equals(oldCustomerName, opObjectName)) {
                    LOG.info("customer update customer name : corpid= " + corpid + ">dataId=" + dataId + ">newName="+ opObjectName + ">oldName="+ oldCustomerName);
                    ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(corpid, dataId, opObjectName);
                    consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.CUSTOMER);
                }
                // api发起
                apiHook(formDataUpdateDTO, updateVO, beforeUpdateVO);

                // 2021/3/3 业务规则
                activeRule(formDataUpdateDTO, beforeUpdateVO, updateVO);
                formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
                formDataUpdateVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
            } else if (Objects.equals(noApprovalRequired, 2)) {
                // 自动拒绝
                formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                formDataUpdateVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
            } else {
                formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                formDataUpdateVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
                PaasProcessDataEntity paasProcessDataEntity = new PaasProcessDataEntity();
                paasProcessDataEntity.setCorpid(formDataUpdateDTO.getCorpid());
                paasProcessDataEntity.setFormDataId(dataId);
                paasProcessDataEntity.setBusinessType(businessType);
                paasProcessDataEntity.setSaasMark(formDataUpdateDTO.getSaasMark());
                proModelService.updateFormDataStatus(paasProcessDataEntity, FlowStatusEnum.IN_APPROVAL.getType());
            }
            if (Objects.nonNull(formDataUpdateDTO.getIsImport()) && Objects.equals(formDataUpdateDTO.getIsImport(),1)) {
                // 客户导入覆盖历史数据时获取经纬度
                Runnable runnable = () -> {
                    try {
                        JSONObject addressObj = beforeUpdateVO.getPaasFormDataEntity().getData().getJSONObject(CustomerManagementEnum.ADDRESS.getAttr());
                        if (Objects.nonNull(addressObj)) {
                            String province = addressObj.getString(PaasConstant.PROVINCE);
                            String city = addressObj.getString(PaasConstant.CITY);
                            String district = addressObj.getString(PaasConstant.DISTRICT);
                            String address = addressObj.getString(PaasConstant.ADDRESS);
                            String addressStr = province + city + district + address;
                            // 去除空格
                            addressStr = addressStr.replaceAll(" +", "");
                            JSONObject oldData = beforeUpdateVO.getOldPaasFormData().getData().getJSONObject(CustomerManagementEnum.ADDRESS.getAttr());
                            String oldProvince = oldData.getString(PaasConstant.PROVINCE);
                            String oldCity = oldData.getString(PaasConstant.CITY);
                            String oldDistrict = oldData.getString(PaasConstant.DISTRICT);
                            String oldAddress = oldData.getString(PaasConstant.ADDRESS);
                            String oldAddressStr = oldProvince + oldCity + oldDistrict + oldAddress;
                            oldAddressStr = oldAddressStr.replaceAll(" +", "");
                            if (StringUtil.isNotEmpty(addressStr) && !Objects.equals(addressStr, oldAddressStr)) {
                                JSONObject location = new JSONObject();
                                JSONObject geo = GaodeGeoHelper.geo(addressStr, "");
                                String latitude = geo.getString("latitude");
                                String longitude = geo.getString("longitude");
                                location.put("lat", latitude);
                                location.put("lon", longitude);
                                addressObj.put("location", location);
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put(CustomerManagementEnum.ADDRESS.getAttr(), addressObj);
                                UpdateDataEntity updateData = ExplainUtil.getUpdateData(beforeUpdateVO.getPaasFormDataEntity().getId(), jsonObject, formDataUpdateDTO.getCorpid());
                                customerModel.updateBatch(Collections.singletonList(updateData), formDataUpdateDTO.getCorpid(), WriteRequest.RefreshPolicy.NONE);
                            }
                        }
                    } catch (Exception e) {
                        LOG.error("customer import fixCustomerCoordinates error", e);
                    }
                };
                threadPoolBeanConfig.importCustomerCoordinatesRabbitMqThreadPool().execute(runnable);
            }
            formDataUpdateVO.setFormDataId(dataId);
            return formDataUpdateVO;
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("customerFormDataUpdateServiceImpl.afterSave 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public void apiHook(FormDataUpdateDTO formDataUpdateDTO, UpdateVO updateVO, BeforeUpdateVO beforeUpdateVO) throws XbbException {
        // 第三方服务
        lowCodeExecuteService(formDataUpdateDTO, updateVO, beforeUpdateVO);
    }

    @Override
    public UpdateVO updateForWorkflow(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        UpdateVO updateVO = null;
        try {
            UserVO userVO = userHelp.getUserName(formDataUpdateDTO.getCorpid(), formDataUpdateDTO.getUserId(), formDataUpdateDTO.getLoginUserName(), beforeUpdateVO.getPaasFormDataEntity().getFlowStatus(), beforeUpdateVO.getPaasFormDataEntity().getCreatorId());
            Integer noApprovalRequired = beforeUpdateVO.getNoApprovalRequired();
            Integer updateLine = 0;
            updateVO = new UpdateVO(noApprovalRequired, formDataUpdateDTO.getDataId(), userVO);

            JSONObject oldData = oldPaasFormDataEntity.getData();

            Long oldLastConnectTime = FastJsonHelper.getLongOrDefaultFromFormData(oldData, CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), 0L);
            JSONObject data = paasFormDataEntity.getData();
            Long newLastConnectTime = FastJsonHelper.getLongOrDefaultFromFormData(data, CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), 0L);

            //保留联系人数据
            JSONArray contact = data.getJSONArray(CustomerManagementEnum.ADD_CONTACT.getAttr());
            data.remove(CustomerManagementEnum.ADD_CONTACT.getAttr());
            FormDataUtil.removeSystemData(data);
            Object richTextData = removeRichText(data);
            if ( oldLastConnectTime > newLastConnectTime ) {
                data.put(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(),oldLastConnectTime);
            }
            data.remove("clueId");
            data.remove("isBringCustomer");
            paasFormDataEntity.setData(data);
            CustomerEntityExt customerEntityExt = new CustomerEntityExt();
            BeanUtil.copyProperties(paasFormDataEntity, customerEntityExt);
            updateLine = customerModel.update(customerEntityExt);

            //先放出联系人，会存入transferData中，只在详情页放开数据，不放开权限
            data.put(CustomerManagementEnum.ADD_CONTACT.getAttr(), contact);
            // 设置属性用于返回
            setPartialAttributes(customerEntityExt.getSubFormData(), customerEntityExt.getData(),
                    customerEntityExt.getUpdateTime(), customerEntityExt.getAddTime(), customerEntityExt.getSerialNo(),
                    customerEntityExt.getDepartmentId(), customerEntityExt.getOwnerId(),
                    paasFormDataEntity, beforeUpdateVO);
            updateVO.setPaasFormDataEntity(paasFormDataEntity);
            //富文本数据保存
            Integer updateRichTextLine = updateFormRichText(formDataUpdateDTO, richTextData);
            //表单数据和富文本数据其中有一个编辑就要进工作流
            updateLine = Objects.equals(updateLine, 1) || Objects.equals(updateRichTextLine, 1) ? 1 : 0;
            updateVO.setUpdateLine(updateLine);
            //文件柜数据保存
//            saveFile(formDataUpdateDTO, paasFormDataEntity, userVO);

            return updateVO;
        } catch (XbbException e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            throw e;
        } catch (Exception e) {
            afterSaveRollBack(formDataUpdateDTO, updateVO, beforeUpdateVO, new ReRollBackEntity());
            LOG.error("customerFormDataUpdateServiceImpl.update 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public FormDataUpdateVO afterSaveForWorkflow(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, UpdateVO updateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        String corpid = formDataUpdateDTO.getCorpid();
        Long dataId = formDataUpdateDTO.getDataId();
        Integer businessType = formDataUpdateDTO.getBusinessType();
        try {
            FormDataUpdateVO formDataUpdateVO = new FormDataUpdateVO();
            SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
            BeanUtil.copyProperties(formDataUpdateDTO, saasFormSaveDTO);
            packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
            // 处理保存之后的逻辑
            customerService.afterSaveForUpdateWorkflow(saasFormSaveDTO);
//

            formDataUpdateVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
            formDataUpdateVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
//            PaasProcessDataEntity paasProcessDataEntity = new PaasProcessDataEntity();
//            paasProcessDataEntity.setCorpid(formDataUpdateDTO.getCorpid());
//            paasProcessDataEntity.setFormDataId(dataId);
//            paasProcessDataEntity.setBusinessType(businessType);
//            paasProcessDataEntity.setSaasMark(formDataUpdateDTO.getSaasMark());
//            proModelService.updateFormDataStatus(paasProcessDataEntity, FlowStatusEnum.IN_APPROVAL.getType());
            formDataUpdateVO.setFormDataId(dataId);
            return formDataUpdateVO;
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("customerFormDataUpdateServiceImpl.afterSave 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public Long backupData(FormDataUpdateDTO formDataUpdateDTO, BeforeUpdateVO beforeUpdateVO, PaasFormEntityExt paasFormEntity, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldFormDataEntity) throws XbbException {
        String corpid = formDataUpdateDTO.getCorpid();
        Integer isApprove = paasFormEntity.getIsProcessForm();
        if (!formDataUpdateDTO.getIsSatisfyTrigger()) {
            return null;
        }
        JSONObject data = oldFormDataEntity.getData();
        setSystemData(data, oldFormDataEntity);
        long now = DateTimeUtil.getInt();
        data = backupDataOtherInfo(data, corpid, oldFormDataEntity.getId());
        WorkflowBackupDataEntity workflowBackupDataEntity = new WorkflowBackupDataEntity(corpid, oldFormDataEntity.getAppId(), oldFormDataEntity.getFormId(), oldFormDataEntity.getMenuId(), 0L, 0L,
                oldFormDataEntity.getId(), data, now, now, DelEnum.NORMAL.getDel());
        workflowBackupDataModel.insert(workflowBackupDataEntity);
        //富文本数据备份
        backupRichText(workflowBackupDataEntity, formDataUpdateDTO.getBusinessType(), formDataUpdateDTO.getSaasMark());
        return workflowBackupDataEntity.getId();
    }

    @Override
    public JSONObject backupDataOtherInfo(JSONObject data, String corpid, Long dataId) {
        List<CustomerUserEntity> contactList = customerUserModel.getByCustomerId(corpid, dataId);
        data.put(StringConstant.USER_TEAM, contactList);
        return data;
    }

    /**
     * 判断当前人有没有编辑的数据权限
     *
     * @param formDataUpdateDTO
     * @param explainMap
     * @param oldPaasFormDataEntity
     * @return
     */
    @Override
    protected void handleEditDataPermission(FormDataUpdateDTO formDataUpdateDTO, Map<String, FieldAttrEntity> explainMap, PaasFormDataEntity oldPaasFormDataEntity) throws XbbException {
        boolean isImport = Objects.equals(formDataUpdateDTO.getIsImport(), 1);
        if (isImport) {
            return;
        }
        boolean customerPublicTag = Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), formDataUpdateDTO.getBusinessType()) &&
                Objects.equals(BasicConstant.ONE, oldPaasFormDataEntity.getData().getInteger(CustomerManagementEnum.IS_PUBLIC.getAttr()));

        if (customerPublicTag) {
            return;
        }
        super.handleEditDataPermission(formDataUpdateDTO, explainMap, oldPaasFormDataEntity);
    }
}
